<template>
  <div>
    <el-alert
      title="1.第一步选择需要排班人员。2.第二步选择需要排班的日期。3.第三步选择需要排班的班次。4.第四部保存设置"
      type="info"
      class="mb10"
      :closable="false">
    </el-alert>
    <el-alert
      title="提示：批量排班无法查看单个人的排班记录"
      type="info"
      class="mb10"
      :closable="false">
    </el-alert>
    <div class="day-scheduling">
      <div class="day-scheduling-l mr20">
        <!--        @selection-change="handleSelectionChange"-->
        <el-table v-loading="loading" :data="teamlist" size="small" border>
          <el-table-column width="75" align="center">
            <template slot-scope="scope">
              <el-radio v-model="chooseUser" :label="scope.row.userId"></el-radio>
            </template>
          </el-table-column>
          <el-table-column label="姓名" align="center" prop="nickName" width="120">
            <template slot-scope="scope">
              {{ `${scope.row.nickName}(${scope.row.isMaster ? '主岗' : '兼岗'})` }}
            </template>
          </el-table-column>
          <el-table-column label="联系电话" align="center" prop="phone" width="100"/>
          <el-table-column label="职务" align="center" prop="pointsId">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_work_post" :value="scope.row.duties"/>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="day-scheduling-r">
        <div class="day-scheduling-r-t mb10">
          <div class="scheduling-header">
            <div class="scheduling-header-name">
              班次:
            </div>
            <div class="scheduling-header-list" v-if="SignCatelist">
              <div class="scheduling-header-list-line" v-for="(item, index) in SignCatelist"
                   :style="{'background': item.color}" @click="checkScheduling(item)">
                <div v-if="item.id">
                  {{ item.name }}
                  {{
                    `${item.comeTime1}-${item.outNext1 ? '次日' : ''}${item.outTime1} ${item.comeTime2 && item.comeNext2 ? '次日' : ''}${item.comeTime2 || ''}${item.comeTime2 ? '-' : ''}${item.outTime2 && item.outNext2 ? '次日' : ''}${item.outTime2 || ''}`
                  }}
                </div>
                <div v-else class="scheduling-header-list-type">
                  {{ item.name }}
                </div>
              </div>
            </div>
            <div v-else class="not-workTime">
              暂无班次信息
            </div>
          </div>
        </div>
        <div class="day-scheduling-r-b">
          <div class="day-scheduling-r-b-top">
            <div class="day-scheduling-r-b-top-l">
              <span class="el-icon-document-checked" @click="checkAll(1)">全选</span>
              <span class="el-icon-delete" @click="checkAll(2)">清空班次</span>
              <span class="el-icon-delete" @click="checkAll(3)">清空选中</span>
            </div>
            <div class="day-scheduling-r-b-top-lr">
              <el-date-picker
                v-model="monthThis"
                size="small"
                type="month"
                format="yyyy-MM"
                value-format="yyyy-MM"
                placeholder="选择月">
              </el-date-picker>
              <!--              <el-date-picker-->
              <!--                v-model="value1"-->
              <!--                size="small"-->
              <!--                type="daterange"-->
              <!--                range-separator="至"-->
              <!--                :picker-options="pickerOptions2"-->
              <!--                format="yyyy-MM-dd"-->
              <!--                value-format="yyyy-MM-dd"-->
              <!--                start-placeholder="开始日期"-->
              <!--                end-placeholder="结束日期">-->
              <!--              </el-date-picker>-->
              <el-button
                class="ml10"
                type="primary"
                icon="el-icon-search"
                size="small"
                @click="handleQuery"
              >搜索
              </el-button>
            </div>
          </div>
          <div class="attendance-body mt10">
            <div class="attendance-box">
              <div class="attendance-box-thead">
                <div class="attendance-box-th" v-for="item in dayMonth" @click="chooseDayFn(item.dayOne)">
                  <div class="attendance-box-th-time">
                    <span>周{{ item.week }}</span>
                    <span>{{ item.dayOne }}</span>
                  </div>
                  <div class="attendance-box-th-box">
                    <template v-if="chooseWork[item.dayOne]">
                      <span
                        :style="{'backgroundColor': chooseWork[item.dayOne]?chooseWork[item.dayOne].color:'','color': chooseWork[item.dayOne]?(chooseWork[item.dayOne].id?'#fff':'#000'):''}">
                      {{ chooseWork[item.dayOne] ? chooseWork[item.dayOne].name : '' }}
                    </span>
                    </template>
                    <em class="iconfont icon-youxiajiaoxuanzhong" v-if="chooseDay.indexOf(item.dayOne)!==-1"></em>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {listStagnationPointUser} from "@/api/system/stagnation_point";
import {listSignCate, listScheduling} from "@/api/system/sign_category";
import {addSchedule, delSchedule} from "@/api/system/scheduling"
import {mapGetters} from 'vuex'

export default {
  dicts: ['sys_work_post'],
  name: "schedulingEdit",
  props: ['pointData'],
  computed: {
    ...mapGetters([
      'deptId'
    ]),
  },
  watch: {
    pointData() {
      // this.listSchedulingFn() // 驻点排班记录
      // this.queryParams.pointsId = this.pointData.id
      // this.getList()
    },
    chooseUser() {
      this.listSchedulingFn(this.chooseUser)
    }
  },
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        pointsId: 0
      },
      queryParamsCate: {
        pageNum: 1,
        pageSize: 100,
        pointsId: 0
      },
      loading: false,
      teamlist: [],
      ids: [],
      pickerOptions2: {
        onPick: function ({minDate, maxDate}) {
          if (minDate && !maxDate) {
            const currentDateTimestamp = minDate.getTime();
            const minDateTimestamp = currentDateTimestamp - 3600 * 1000 * 24 * 31;
            const maxDateTimestamp = currentDateTimestamp + 3600 * 1000 * 24 * 31;
            this.disabledDate = date => {
              const dateTimestamp = date.getTime();
              return dateTimestamp <= minDateTimestamp || dateTimestamp >= maxDateTimestamp;
            };
          }
        }
      },
      options: [],
      value: '',
      monthThis: '',
      value1: '',
      dayMonth: [],
      SignCatelist: null,
      checked: false,
      color: ['#457eca', '#ad6acd', '#cfe375','#ca6f45', '#ad6acd', '#ad6acd'],
      chooseUser: 0, // 选中的用户
      chooseDay: [], // 选中的日期
      chooseWork: {}, // 日期安排的班次
      flag: true
    }
  },
  created() {
    // 一进入进行日期的筛选
    console.log('pointData==>', this.pointData)
    // this.queryParams.pointsId = this.paramId
    this.queryParams.pointsId = this.pointData?this.pointData.id:0
    this.queryParamsCate.pointsId = this.pointData?this.pointData.id:0
    this.getList()
    this.getSchedulingList() // 当前驻点班次
    let tiem_ = this.newDate().split('-')
    this.monthThis = tiem_.join('-')
    this.getDaysOfWeek(tiem_[0], tiem_[1])
  },
  methods: {
    // 保存排班设置
    saveScheduleFn() {
      let that = this
      if (!this.chooseUser) {
        this.$message.error('选择需要排班的人员')
        return
      }
      if (JSON.stringify(this.chooseWork) == '{}') {
        this.$message.error('选择需要排班的日期班次')
        return
      }
      let data_ = []
      let b_ = this.monthThis.split('-').join('')
      for (let index in this.chooseWork) {
        let item = this.chooseWork[index]
        data_.push({
          cateId: item.id, // 考勤方案id
          userId: this.chooseUser, // 用户id
          month: b_, // 月份
          day: index < 10 ? `${b_}0${index}` : `${b_}${index}`, // 日期
          projectId: this.pointData.projectId, //项目id
          pointsId: this.pointData.id, //驻点id
          deptId: this.deptId
        })
      }
      if (this.flag) {
        this.flag = false
      }
      addSchedule({schedulings: data_}).then(res => {
        // 刷新页面，更新当前用户的排班记录
        console.log('res==>', res)
        this.$message.success('保存成功！')
        this.chooseDay = []
        setTimeout(() => {
          that.flag = true
        }, 1000)
      })
    },
    /** zhuqi */
    listSchedulingFn(userId) {
      let data_ = {
        pageNum: 1,
        pageSize: 1000,
        pointsId: this.pointData.id, //  驻点
        month: this.monthThis.split('-').join(''), // 月份
      }
      if (userId) {
        data_.userId = userId
      }
      listScheduling(data_).then(res => {
        // userId day
        let user_ = {}
        for (let item of res.rows) {
          if (!user_[item.userId]) {
            user_[item.userId] = {}
          }
          let str_day = item.day.slice(-2);
          user_[item.userId][parseInt(str_day)] = item
        }
        // chooseWork: {} // 日期安排的班次
        let day_val = {}
        for (let index in user_[userId]) {
          let row_ = user_[userId][index]
          day_val[index] = this.SignCatelist[row_.cateId]
        }
        // if(JSON.stringify(day_val)!=='{}'){
        this.chooseWork = this.$deepCopy(day_val)
        // }
        // this.monthScheduList = JSON.stringify(user_)!=='{}'?user_:null
        // this.flagTime = true
        // 需要将数据分配给各个用户身上
      })
    },
    // 选择班次
    checkScheduling(work) {
      // 根据选中的班次进行排班 chooseDay;
      for (let item of this.chooseDay) {
        this.$set(this.chooseWork, item, this.$deepCopy(work))
      }
      console.log('当前选择：', this.chooseWork)
    },
    checkAll(type) {
      // 1 全选 2 清空班次 3 清空选中
      if (type == 1) {
        for (let item of this.dayMonth) {
          if (this.chooseDay.indexOf(item.dayOne) == -1) {
            this.chooseDay.push(item.dayOne)
          }
        }
      } else if (type == 2) {
        this.chooseWork = {}
      } else if (type == 3) {
        this.chooseDay = []
      }
    },
    chooseDayFn(day) {
      if (!this.chooseUser) {
        this.$message.error('选择需要排班的人员')
        return
      }
      if (this.chooseDay.indexOf(day) == -1) {
        this.chooseDay.push(day)
      } else {
        this.chooseDay.splice(this.chooseDay.indexOf(day), 1)
      }
      console.log('this.chooseDay:', this.chooseDay)
    },
    /** 变更日期 */
    handleQuery() {
      console.log('$getDayAll:', this.$getDayAll(this.value1[0], this.value1[1]))
      let tiem_ = this.monthThis.split('-')
      this.getDaysOfWeek(tiem_[0], tiem_[1])
    },
    /** 班次 */
    getSchedulingList() {
      this.loading = true;
      listSignCate(this.queryParamsCate).then(response => {
        console.log('response==>', response)
        if (response.rows.length) {
          let list_ = {}
          list_[0] = {
            id: 0,
            name: '休息',
            color: '#ddd'
          }
          for (let index in response.rows) {
            let item = response.rows[index]
            item.color = this.color[index]
            list_[item.id] = item
          }
          console.log('list_:', list_)
          this.SignCatelist = list_;
        }
      });
    },
    /** 多人团队人员 */
    // getUserList() {
    //   this.loading = true;
    //   listStagnationPointUser({
    //     pageNum: 1,
    //     pageSize: 200,
    //     pointsId: this.pointData.id, //  驻点
    //   }).then(response => {
    //     for (let item of response.rows) {
    //       item.dayScheduling = {}
    //     }
    //     this.teamlist = response.rows;
    //     this.listSchedulingFn() // 整个驻点的排班
    //   });
    // },
    newDate() {
      let date = new Date()
      let y = date.getFullYear()
      let m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      return y + '-' + m
    },
    getDaysOfWeek(year, month) {
      let week = ['日', '一', '二', '三', '四', '五', '六']
      let dayMonth = []
      let d = new Date(year, month, 0)
      let day = d.getDate();
      this.widthTable = day * 60 + 100
      let firstDayOfMonth = new Date(year, month - 1, 1)
      //该月第一天是周几?0表示周日，1表示周一...6表示周六
      let dayWeek = firstDayOfMonth.getDay()
      for (let i = 0; i < day; i++) {
        dayMonth.push({
          day: `${year}-${month}-${i + 1}`,
          dayOne: i + 1,
          month: month,
          week: week[dayWeek],
          dayName: i + 1
        })
        dayWeek++
        if (dayWeek > 6) {
          dayWeek = 0
        }
      }
      this.dayMonth = dayMonth
      console.log('当前月份信息', this.dayMonth)
    },
    getList() {
      this.loading = true
      listStagnationPointUser(this.queryParams).then(response => {
        console.log('当前队员信息', response.rows)
        this.teamlist = response.rows;
        this.loading = false
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log('selection==>', selection)
      this.ids = selection.map(item => item.postId)
    },
    // /** 排序触发事件 */
    // handleSortChange(column, prop, order) {
    //   this.queryParams.orderByColumn = column.prop;
    //   this.queryParams.isAsc = column.order;
    //   this.getList();
    // }
  }
}
</script>

<style scoped>
.day-scheduling {
  display: flex;
}

.day-scheduling-l {
  background: #f4f4f4;
}

.day-scheduling-r {
  flex: 1;
}

.day-scheduling-r-t {
  padding-top: 10px;
  border-bottom: 1px dashed #ddd;
}

.day-scheduling-r-b {
}

.attendance-box-thead {
  font-size: 12px;
  overflow: hidden;
  text-align: center;
  border-left: 1px solid #f4f4f4;
}

.attendance-box-th {
  display: flex;
  flex-direction: column;
  width: 70px;
  float: left;
  border-right: 1px solid #f4f4f4;
  border-bottom: 1px solid #f4f4f4;
}

.attendance-box-th:hover {
  background: #ffba00;
  cursor: pointer;
}

.scheduling-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.scheduling-header-name {
  margin-right: 10px;
  width: 50px;
  margin-bottom: 10px;
}

.scheduling-header-list {
  /*display: flex;*/
  overflow: hidden;
  flex: 1;
}

.scheduling-header-list-line {
  margin-right: 10px;
  padding: 3px 10px;
  border-radius: 5px;
  color: #fff;
  cursor: pointer;
  margin-bottom: 10px;
  float: left;
}

.scheduling-header-list-line:hover {
  text-decoration: underline;
}

.scheduling-header-list-type {
  color: #000;
}

.attendance-box-th-time {
  background: #f8f8f8;
  display: flex;
  flex-direction: column;
  padding: 8px 0;
  color: #000;
}

.attendance-box-th-box {
  height: 60px;
  position: relative;
}

.attendance-box-th-box span {
  display: block;
  height: 60px;
  line-height: 60px;
  width: 100%;
}

.attendance-box-th-box em {
  color: #04ae0f;
  position: absolute;
  right: 0;
  bottom: 0;
  font-size: 18px;
}

.day-scheduling-r-b-top {
  display: flex;
  align-items: center;
}

.day-scheduling-r-b-top-l {
  flex: 1;
}

.day-scheduling-r-b-top-l span {
  font-size: 14px;
  margin-right: 10px;
  cursor: pointer;
}

.day-scheduling-r-b-top-l span:hover {
  text-decoration: underline;
}

.day-scheduling-r-b-top-lr {

}

.not-workTime {
  color: #ddd;
  margin-bottom: 10px;
}

</style>
